<template>
  <div>
    <el-form
      ref="form"
      v-loading="loading"
      :model="form"
      :rules="rules"
      size="small"
      label-width="150px"
    >
      <el-form-item label="开启同城配送：" prop="status">
        <el-switch
          v-model="form.status"
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item>

      <div v-if="form.status">
        <el-form-item label="起送价：" prop="minPrice">
          <el-input
            v-model.trim="form.minPrice"
            placeholder="请输入起送价"
            maxlength="10"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <el-form-item label="基础配送费：" prop="freightFee">
          <el-input
            v-model.trim="form.freightFee"
            placeholder="请输入基础配送费"
            maxlength="10"
          >
            <template slot="append">元</template>
          </el-input>
          <div>
            填写后，顾客下单时如果配送费用少于基础配送费，将会按基础配送费计算
          </div>
        </el-form-item>
        <el-form-item label="开启备货时间：" prop="limitTime">
          <el-switch v-model="form.limitTime" />
          <div>开启后，买家在下单可选择配送时间</div>
        </el-form-item>

        <div v-if="form.limitTime">
          <el-form-item label="商品备货规则：" prop="prepayTimeUnit">
            <el-select v-model="form.prepayTimeUnit" placeholder="请选择">
              <el-option value="HOURS" label="按小时计算备货时间" />
              <el-option
                value="DAYS"
                label="按天计算备货时间"
              /> </el-select>&nbsp;
            <el-form-item class="app-display-i-b" prop="prepayTime">
              <el-input v-model="form.prepayTime" placeholder="请输入">
                <template slot="append">{{
                  form.prepayTimeUnit === "HOURS" ? "小时" : "天"
                }}</template>
              </el-input>
            </el-form-item>
          </el-form-item>
          <el-form-item label="可预约发货时间：" prop="bookingDays">
            <el-input
              v-model="form.bookingDays"
              placeholder="0代表24小时内"
              maxlength="2"
            >
              <template slot="append">天</template>
            </el-input>
          </el-form-item>
          <el-form-item label="配送时段：" prop="serviceTimeList">
            <el-card
              v-for="(item, index) in form.serviceTimeList"
              :key="index"
              class="nest-card-box"
            >
              <div class="flexRBC">
                <span>时段 {{ index + 1 }}</span>
                <el-button
                  v-if="form.serviceTimeList.length > 1"
                  type="text"
                  icon="el-icon-delete"
                  class="app-text-color-danger"
                  @click="delServiceTime(index)"
                >删除</el-button>
              </div>
              <el-form-item
                :prop="'serviceTimeList.' + index + '.weekDays'"
                :rules="rules.serviceWeekDays"
              >
                <el-checkbox-group v-model="item.weekDays">
                  <el-checkbox-button
                    v-for="(dayItem, dayIndex) in weekOptions"
                    :key="dayIndex"
                    :label="String(dayItem.label)"
                  >{{ dayItem.value }}</el-checkbox-button>
                </el-checkbox-group>
              </el-form-item>

              <el-form-item
                :prop="'serviceTimeList.' + index + '.time'"
                :rules="rules.serviceTime"
              >
                <el-time-picker
                  v-model="item.time"
                  is-range
                  value-format="HH:mm"
                  format="HH:mm"
                  range-separator="~"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围"
                />
              </el-form-item>
            </el-card>
            <el-button
              type="text"
              icon="el-icon-plus"
              style="display: block"
              @click="addServiceTime"
            >增加时间段</el-button>
          </el-form-item>
        </div>

        <el-form-item label="配送方式：" prop="localDeliveryType">
          <el-select v-model="form.localDeliveryType" placeholder="请选择">
            <el-option :value="0" label="商家配送" />
            <el-option :value="1" label="第三方配送" />
          </el-select>
        </el-form-item>

        <el-form-item label="配送距离：" prop="aresRadius">
          <el-input
            v-model.trim="form.aresRadius"
            placeholder="请输入配送距离"
            maxlength="5"
          >
            <template slot="append">KM</template>
          </el-input>
        </el-form-item>

        <el-form-item label="订单取消规则：" prop="cancelRule">
          <el-select v-model="form.cancelRule" placeholder="请选择" style="width:250px">
            <el-option :value="1" label="支付后订单不可取消" />
            <el-option :value="0" label="支付后可免费取消订单" />
            <el-option :value="2" label="取消订单需要扣除违约金" />
          </el-select>
          <span v-if="form.cancelRule===2">&nbsp;违约金额为订单实付金额的&nbsp;</span>
          <el-form-item v-if="form.cancelRule===2" class="app-display-i-b" prop="cancelFeeRatio">
            <el-input v-model="form.cancelFeeRatio" placeholder="请输入">
              <template slot="append">%</template>
            </el-input>
          </el-form-item>
        </el-form-item>

        <el-form-item label="下单提示：" prop="remark">
          <el-input
            v-model="form.remark"
            :autosize="{ minRows: 2, maxRows: 6 }"
            type="textarea"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </div>

      <el-form-item>
        <el-button type="primary" round @click="submit">保存配置</el-button>
        <el-button round @click="fetchData">重置配置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  getDeliveryConfig,
  saveDeliveryConfig
} from '@/views/wxaMallModule/api/delivery'
import { changeMinToHourMin, changeHourMinToMin } from '@/utils/format'
import {
  validateCustomTwoDecimal,
  validateCustomADecimal,
  validateCustomPositiveInt
} from '@/utils/validate.js'
import validatorMixin from './validatorMixin.js'
export default {
  mixins: [validatorMixin],
  props: {
    activeStore: {
      type: Object
    }
  },
  data() {
    // 校验方法
    const validatorMinPrice = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入起送价'))
      } else if (!validateCustomTwoDecimal(value, 7, [0])) {
        callback(new Error('请输入0，正整数，正小数（小数位不超过2位））'))
      } else {
        callback()
      }
    }
    const validatorFreightFee = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入基础配送费'))
      } else if (!validateCustomTwoDecimal(value, 7, [0])) {
        callback(new Error('请输入0，正整数，正小数（小数位不超过2位））'))
      } else {
        callback()
      }
    }

    const validatorAresRadius = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入配送距离'))
      } else if (!validateCustomADecimal(value, 7)) {
        callback(new Error('请输入正整数，正小数（小数位不超过1位））'))
      } else {
        callback()
      }
    }

    const validatorCancelFeeRatio = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入'))
      } else if (!validateCustomPositiveInt(value, 2, [100])) {
        callback(new Error('请输入1~100'))
      } else {
        callback()
      }
    }
    return {
      // 校验字段
      rules: {
        minPrice: [
          {
            required: true,
            validator: validatorMinPrice,
            trigger: ['blur', 'change']
          }
        ],
        freightFee: [
          {
            required: true,
            validator: validatorFreightFee,
            trigger: ['blur', 'change']
          }
        ],
        serviceTimeList: [
          {
            type: 'array',
            required: true,
            message: '请设置配送时段',
            trigger: ['blur', 'change']
          }
        ],
        serviceWeekDays: [
          {
            type: 'array',
            required: true,
            message: '请选择时段',
            trigger: ['blur', 'change']
          }
        ],
        serviceTime: [
          {
            required: true,
            message: '请选择时间',
            trigger: ['blur', 'change']
          }
        ],
        localDeliveryType: [
          {
            required: true,
            message: '请选择配送方式',
            trigger: ['blur', 'change']
          }
        ],
        aresRadius: [
          {
            required: true,
            validator: validatorAresRadius,
            trigger: ['blur', 'change']
          }
        ],
        cancelRule: [
          {
            required: true,
            message: '请选择',
            trigger: ['blur', 'change']
          }
        ],
        cancelFeeRatio: [
          {
            required: true,
            validator: validatorCancelFeeRatio,
            trigger: ['blur', 'change']
          }
        ]
      },
      // 配置
      weekOptions: [
        { value: '周一', label: 1 },
        { value: '周二', label: 2 },
        { value: '周三', label: 3 },
        { value: '周四', label: 4 },
        { value: '周五', label: 5 },
        { value: '周六', label: 6 },
        { value: '周日', label: 0 }
      ],
      // 状态
      loading: false,
      // 数据
      form: {
        status: 0,
        remark: null,
        minPrice: null,
        freightFee: null,
        limitTime: false,
        prepayTimeUnit: 'HOURS',
        prepayTime: null,
        bookingDays: 0,
        serviceTimeList: [
          {
            time: ['00:00', '23:59'],
            weekDays: ['0', '1', '2', '3', '4', '5', '6']
          }
        ],
        localDeliveryType: 0,
        areaType: 0,
        aresRadius: 0,
        aresPointList: [],
        cancelRule: 1,
        cancelFeeRatio: null,
        type: 'LOCAL'
      }
    }
  },
  computed: {},
  watch: {
    activeStore(newVal, oldVal) {
      if (newVal.storeId !== oldVal.storeId) {
        this.fetchData()
      }
    }
  },
  created() {},
  mounted() {
    this.fetchData()
  },
  methods: {
    /**
       * 数据组
       */
    // 获取数据
    fetchData() {
      this.loading = true
      getDeliveryConfig({ storeId: this.activeStore.storeId })
        .then((res) => {
          const data = res.data.local
          if (data) {
            data.minPrice = data.minPrice / 100
            data.freightFee = data.freightFee / 100
            data.aresRadius = data.aresRadius / 1000
            data.serviceTimeList.forEach((v) => {
              v.time = [
                changeMinToHourMin(v.beginTime),
                changeMinToHourMin(v.endTime)
              ]
              v.weekDays = v.weekDays.split(',')
            })
            this.form = data
          } else {
            this.form = {
              status: 0,
              remark: null,
              minPrice: null,
              freightFee: null,
              limitTime: false,
              prepayTimeUnit: 'HOURS',
              prepayTime: null,
              serviceTimeList: [
                {
                  time: ['00:00', '23:59'],
                  weekDays: ['0', '1', '2', '3', '4', '5', '6']
                }
              ],
              localDeliveryType: 0,
              areaType: 0,
              aresRadius: 0,
              aresPointList: [],
              cancelRule: 1,
              cancelFeeRatio: null,
              type: 'LOCAL'
            }
          }
        })
        .catch((err) => {})
        .finally(() => {
          this.loading = false
        })
    },

    /**
       * 按钮组
       */
    // 新增服务时间
    addServiceTime() {
      this.form.serviceTimeList.push({
        time: ['00:00', '23:59'],
        weekDays: []
      })
    },

    // 删除服务时间
    delServiceTime(index) {
      this.form.serviceTimeList.splice(index, 1)
    },

    // 提交
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.form))
          if (params.status) {
            if (!params.limitTime) {
              params.serviceTimeList = []
              params.prepayTimeUnit = null
              params.prepayTime = null
            } else {
              params.serviceTimeList.forEach((v) => {
                v.beginTime = changeHourMinToMin(v.time[0])
                v.endTime = changeHourMinToMin(v.time[1])
                v.weekDays = v.weekDays.join(',')
              })
            }
            if (params.cancelRule !== 2) {
              params.cancelFeeRatio = null
            }
            params.minPrice = this.$math.mul(params.minPrice, 100, 0) // 转化分;
            params.freightFee = this.$math.mul(params.freightFee, 100, 0) // 转化分;
            params.aresRadius = this.$math.mul(params.aresRadius, 1000, 0) // 转化米;
          } else {
            params = { status: 0, type: 'LOCAL' }
          }
          params.freightType = 1
          params.storeId = params.storeId || this.activeStore.storeId
          this.loading = true
          saveDeliveryConfig(params)
            .then((res) => {
              this.$notify({
                title: '成功',
                message: '保存成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
            })
            .catch((err) => {})
            .finally(() => {
              this.loading = false
            })
        }
      })
    }

    /**
       * 状态组
       */

    /**
       * 方法组
       */
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .el-textarea {
    width: 500px;
  }
  .el-input,
  .el-select {
    width: 200px;
  }

  /* 嵌套盒子 */
  .nest-card-box {
    width: 80%;
    min-width: 600px;
    max-width: 800px;
    &:not(:last-child) {
      margin-bottom: 10px;
    }
    ::v-deep .el-card {
      margin-bottom: 10px;
    }
  }
</style>
